from nicegui import ui
import plotly.graph_objects as go

# 存储点的列表
points = []

# 初始化 Plotly 图
fig = go.Figure()

# 更新图的函数
def update_graph():
    global fig
    fig.data = []  # 清空之前的点
    if points:
        x_vals = [p[0] for p in points]
        y_vals = [p[1] for p in points]
        z_vals = [p[2] for p in points]
        fig.add_trace(go.Scatter3d(x=x_vals, y=y_vals, z=z_vals, mode='markers', marker=dict(size=5)))
    plot.update()

# 添加点的函数
def add_point():
    try:
        x = float(x_input.value)
        y = float(y_input.value)
        z = float(z_input.value)
        points.append((x, y, z))  # 添加到点列表
        update_graph()  # 更新图
    except ValueError:
        ui.notify("Please enter valid numbers for x, y, and z.", type='negative')

# 删除最后一个点的函数
def delete_last_point():
    if points:
        points.pop()  # 删除最后一个点
        update_graph()  # 更新图
    else:
        ui.notify("No points to delete.", type='warning')

# 创建 NiceGUI 界面
with ui.card():
    x_input = ui.input(label="X", placeholder="Enter X coordinate")
    y_input = ui.input(label="Y", placeholder="Enter Y coordinate")
    z_input = ui.input(label="Z", placeholder="Enter Z coordinate")
    ui.button("Add Point", on_click=add_point)
    ui.button("Delete Last Point", on_click=delete_last_point)

# 显示图
plot = ui.plotly(fig).classes('w-full h-96')

# 启动 NiceGUI 应用
ui.run()